<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实时聊天应用</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .chat-container {
            width: 100%;
            max-width: 1200px;
            height: 80vh;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
            display: flex;
            overflow: hidden;
        }

        .sidebar {
            width: 350px;
            background: #f8f9fa;
            border-right: 1px solid #e9ecef;
            display: flex;
            flex-direction: column;
            position: relative;
        }

        .sidebar-header {
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .friend-requests-button {
            background: rgba(255, 255, 255, 0.2);
            border: none;
            border-radius: 50%;
            width: 36px;
            height: 36px;
            color: white;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
        }

        .friend-requests-button:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        .requests-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #ff4757;
            color: white;
            font-size: 10px;
            padding: 2px 6px;
            border-radius: 10px;
            min-width: 16px;
            text-align: center;
        }

        .friend-requests-list {
            position: absolute;
            top: 100px;
            right: 20px;
            background: white;
            color: #333;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            width: 300px;
            max-height: 400px;
            overflow-y: auto;
            display: none;
            z-index: 100;
        }

        .friend-requests-list.show {
            display: block;
        }

        .friend-requests-header {
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            font-weight: bold;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .friend-request-item {
            padding: 15px 20px;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .friend-request-item:last-child {
            border-bottom: none;
        }

        .friend-request-info {
            display: flex;
            align-items: center;
        }

        .friend-request-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #667eea;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
        }

        .friend-request-actions {
            display: flex;
            gap: 5px;
        }

        .accept-button, .reject-button {
            padding: 5px 12px;
            border: none;
            border-radius: 15px;
            cursor: pointer;
            font-size: 12px;
        }

        .accept-button {
            background: #2ed573;
            color: white;
        }

        .reject-button {
            background: #ff4757;
            color: white;
        }

        .add-friend-button {
            background: #667eea;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 15px;
            cursor: pointer;
            font-size: 12px;
            margin-left: 10px;
        }

        .user-search-container {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            display: none;
        }

        .user-search-modal {
            background: white;
            border-radius: 15px;
            width: 90%;
            max-width: 400px;
            max-height: 80vh;
            display: flex;
            flex-direction: column;
        }

        .user-search-header {
            padding: 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .user-search-header h3 {
            margin: 0;
        }

        .close-button {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #666;
        }

        .user-search-input-container {
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
        }

        .user-search-input {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 25px;
            font-size: 14px;
            outline: none;
        }

        .user-search-results {
            flex: 1;
            overflow-y: auto;
            padding: 10px 0;
        }

        .user-search-result-item {
            padding: 15px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            cursor: pointer;
        }

        .user-search-result-item:hover {
            background: #f5f5f5;
        }

        .user-search-info {
            display: flex;
            align-items: center;
        }

        .user-search-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #667eea;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
        }

        .no-results {
            text-align: center;
            color: #999;
            padding: 30px;
        }

        .user-info {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .user-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }

        .user-details h3 {
            margin: 0;
            font-size: 16px;
        }

        .user-details p {
            margin: 0;
            font-size: 12px;
            opacity: 0.8;
        }

        .search-box {
            padding: 15px 20px;
            background: white;
            border-bottom: 1px solid #e9ecef;
        }

        .search-input {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 25px;
            font-size: 14px;
            outline: none;
            transition: border-color 0.3s;
        }

        .search-input:focus {
            border-color: #667eea;
        }

        .contacts-list {
            flex: 1;
            overflow-y: auto;
        }

        .contact-item {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
            border-bottom: 1px solid #f1f3f4;
        }

        .contact-item:hover {
            background-color: #f8f9fa;
        }

        .contact-item.active {
            background-color: #e3f2fd;
            border-left: 4px solid #667eea;
        }
        
        /* 未读消息徽章 */
        .unread-badge {
            min-width: 20px;
            height: 20px;
            background-color: #e53935;
            color: white;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
            margin-left: 8px;
            padding: 0 6px;
        }

        .contact-avatar {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            margin-right: 12px;
        }

        .contact-info {
            flex: 1;
        }

        .contact-name {
            font-weight: 600;
            color: #333;
            margin-bottom: 2px;
        }

        .contact-status {
            font-size: 12px;
            color: #666;
        }

        .contact-status.online {
            color: #4caf50;
        }

        .contact-status.offline {
            color: #999;
        }

        .chat-area {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .chat-header {
            padding: 20px;
            background: white;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .chat-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }

        .chat-status {
            font-size: 14px;
            color: #666;
        }

        .messages-container {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: #f8f9fa;
        }

        .message {
            margin-bottom: 15px;
            display: flex;
            align-items: flex-end;
        }

        .message.sent {
            justify-content: flex-end;
        }

        .message.received {
            justify-content: flex-start;
        }

        .message-bubble {
            max-width: 60%;
            padding: 12px 16px;
            border-radius: 18px;
            font-size: 14px;
            line-height: 1.4;
            word-wrap: break-word;
        }

        .message.sent .message-bubble {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-bottom-right-radius: 4px;
        }

        .message.received .message-bubble {
            background: linear-gradient(135deg, #e6f3ff 0%, #cce7ff 100%);
            color: #1a365d;
            border: 1px solid #90cdf4;
            border-bottom-left-radius: 4px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
        }

        .message-time {
            font-size: 11px;
            color: #999;
            margin: 0 8px;
        }

        .message-input-area {
            padding: 20px;
            background: white;
            border-top: 1px solid #e9ecef;
        }

        .input-container {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .message-input {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid #ddd;
            border-radius: 25px;
            font-size: 14px;
            outline: none;
            transition: border-color 0.3s;
        }

        .message-input:focus {
            border-color: #667eea;
        }

        .send-button, .attach-button {
            width: 40px;
            height: 40px;
            border: none;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: transform 0.2s;
        }

        .send-button:hover, .attach-button:hover {
            transform: scale(1.1);
        }

        .login-container {
            width: 100%;
            max-width: 400px;
            padding: 40px;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
            text-align: center;
        }

        .login-form {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .form-group {
            text-align: left;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #333;
        }

        .form-group input {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 14px;
            outline: none;
            transition: border-color 0.3s;
        }

        .form-group input:focus {
            border-color: #667eea;
        }

        .login-button {
            padding: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .login-button:hover {
            transform: translateY(-2px);
        }

        .login-button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .empty-state {
            text-align: center;
            color: #999;
            padding: 40px;
            font-size: 16px;
        }

        .typing-indicator {
            display: none;
            align-items: center;
            gap: 5px;
            padding: 10px 15px;
            background: white;
            border-radius: 15px;
            margin-bottom: 10px;
            font-size: 12px;
            color: #666;
        }

        .typing-dots {
            display: flex;
            gap: 2px;
        }

        .typing-dot {
            width: 4px;
            height: 4px;
            background: #999;
            border-radius: 50%;
            animation: typing 1.4s infinite ease-in-out;
        }

        .typing-dot:nth-child(1) { animation-delay: -0.32s; }
        .typing-dot:nth-child(2) { animation-delay: -0.16s; }

        @keyframes typing {
            0%, 80%, 100% {
                transform: scale(0);
                opacity: 0.5;
            }
            40% {
                transform: scale(1);
                opacity: 1;
            }
        }

        .file-upload {
            display: none;
        }

        .message-image {
            max-width: 100%;
            max-height: 200px;
            border-radius: 8px;
            cursor: pointer;
            display: block;
            height: auto;
        }

        .message-file {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 12px;
            background: rgba(0, 0, 0, 0.05);
            border-radius: 8px;
            cursor: pointer;
        }

        .message-file i {
            font-size: 20px;
            color: #667eea;
        }

        .message-audio {
            width: 200px;
            height: 40px;
        }

        .hidden {
            display: none;
        }

        .loading {
            text-align: center;
            padding: 20px;
            color: #999;
        }

        .spinner {
            border: 2px solid #f3f3f3;
            border-top: 2px solid #667eea;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .error-message {
            background: #fee;
            color: #c33;
            padding: 10px;
            border-radius: 8px;
            margin: 10px 0;
            text-align: center;
        }

        .success-message {
            background: #efe;
            color: #3c3;
            padding: 10px;
            border-radius: 8px;
            margin: 10px 0;
            text-align: center;
        }

        .mobile-back-button {
            display: none;
            background: none;
            border: none;
            color: #667eea;
            font-size: 20px;
            cursor: pointer;
            padding: 5px;
            margin-right: 10px;
        }
        
        .mobile-tip {
            display: none;
        }
        
        .desktop-tip {
            display: inline;
        }
        
        @media (max-width: 768px) {
            .chat-container {
                height: 100vh;
                border-radius: 0;
            }
            
            .sidebar {
                width: 100%;
                position: absolute;
                left: -100%;
                transition: left 0.3s;
                z-index: 1000;
            }
            
            .sidebar.active {
                left: 0;
            }
            
            .chat-area {
                width: 100%;
            }
            
            .mobile-back-button {
                display: inline-block !important;
            }
            
            .mobile-tip {
                display: inline !important;
            }
            
            .desktop-tip {
                display: none !important;
            }
        }
        
        @media (min-width: 769px) {
            .mobile-back-button {
                display: none !important;
            }
            
            .mobile-tip {
                display: none !important;
            }
            
            .desktop-tip {
                display: inline !important;
            }
        }
    </style>
</head>
<body>
    <div id="app">
        <!-- 登录页面 -->
        <div id="loginPage" class="login-container">
            <h2 style="margin-bottom: 30px; color: #333;">实时聊天应用</h2>
            <form id="loginForm" class="login-form" onsubmit="handleLogin(event)">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" name="username" required placeholder="请输入用户名">
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" name="password" required placeholder="请输入密码">
                </div>
                <button type="submit" class="login-button">登录</button>
                <div id="loginMessage" style="margin-top: 10px; font-size: 14px;"></div>
            </form>
            <p style="margin-top: 20px; font-size: 14px; color: #666;">
                还没有账号？<a href="register.html" style="color: #667eea; text-decoration: none;">立即注册</a>
            </p>
        </div>

        <!-- 聊天页面 -->
        <div id="chatPage" class="chat-container hidden">
            <div class="sidebar">
                <div class="sidebar-header">
                    <div class="user-info">
                        <div class="user-avatar">
                            <i class="fas fa-user"></i>
                        </div>
                        <div class="user-details">
                            <h3 id="currentUserName">用户名</h3>
                            <p>在线</p>
                        </div>
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <button onclick="showAddFriendModal()" title="添加好友" style="background: rgba(255,255,255,0.2); border: none; color: white; cursor: pointer; font-size: 16px; width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                                <i class="fas fa-user-plus"></i>
                            </button>
                            <button id="friendRequestsButton" onclick="toggleFriendRequests()" title="好友请求" class="friend-requests-button">
                                <i class="fas fa-bell"></i>
                                <span id="requestsBadge" class="requests-badge" style="display: none;">0</span>
                            </button>
                            <button onclick="logout()" title="退出登录" style="background: none; border: none; color: white; cursor: pointer; font-size: 16px;">
                                <i class="fas fa-sign-out-alt"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="search-box">
                    <input type="text" class="search-input" placeholder="搜索好友..." onkeyup="searchContacts(this.value)">
                </div>
                
                <div class="contacts-list" id="contactsList">
                    <div class="loading">
                        <div class="spinner"></div>
                        加载好友中...
                    </div>
                </div>

                <!-- 好友请求列表 -->
                <div id="friendRequestsList" class="friend-requests-list">
                    <div class="friend-requests-header">
                        <span>好友请求</span>
                        <button class="close-button" onclick="toggleFriendRequests()">&times;</button>
                    </div>
                    <div id="friendRequestsContent" class="friend-requests-content">
                        <div class="no-requests">暂无好友请求</div>
                    </div>
                </div>
            </div>

            <div class="chat-area">
                <div class="chat-header">
                    <div style="display: flex; align-items: center;">
                        <button class="mobile-back-button" onclick="showContactsList()" title="返回联系人列表">
                            <i class="fas fa-arrow-left"></i>
                        </button>
                        <div>
                            <div class="chat-title" id="chatTitle">选择联系人开始聊天</div>
                            <div class="chat-status" id="chatStatus">在线</div>
                        </div>
                    </div>
                    <div>
                        <button class="attach-button" onclick="document.getElementById('fileUpload').click()" title="发送文件">
                            <i class="fas fa-paperclip"></i>
                        </button>
                    </div>
                </div>

                <div class="messages-container" id="messagesContainer">
                    <div class="empty-state">
                        <i class="fas fa-comments" style="font-size: 48px; color: #ddd; margin-bottom: 10px;"></i>
                        <p>选择一个联系人开始聊天</p>
                        <p style="font-size: 14px; color: #999; margin-top: 10px;">
                            <span class="mobile-tip">👈 点击左上角箭头返回联系人列表</span>
                            <span class="desktop-tip">从左侧列表中选择联系人</span>
                        </p>
                    </div>
                </div>

                <div class="typing-indicator" id="typingIndicator">
                    <span>对方正在输入</span>
                    <div class="typing-dots">
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                    </div>
                </div>

                <div class="message-input-area">
                    <div class="input-container">
                        <input type="file" id="fileUpload" class="file-upload" accept="image/*,audio/*,video/*,.pdf,.doc,.docx" onchange="handleFileUpload(event)">
                        <input type="text" class="message-input" id="messageInput" placeholder="输入消息..." onkeypress="handleKeyPress(event)">
                        <button class="send-button" onclick="sendMessage()" title="发送消息">
                            <i class="fas fa-paper-plane"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加好友模态框 -->
    <div id="userSearchContainer" class="user-search-container">
        <div class="user-search-modal">
            <div class="user-search-header">
                <h3>搜索用户</h3>
                <button class="close-button" onclick="hideAddFriendModal()">&times;</button>
            </div>
            <div class="user-search-input-container">
                <input type="text" id="userSearchInput" class="user-search-input" placeholder="输入用户名搜索..." onkeyup="searchUsers(this.value)">
            </div>
            <div id="userSearchResults" class="user-search-results">
                <div class="loading">
                    <div class="spinner"></div>
                    输入用户名进行搜索
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.js"></script>
    <script>
        // 全局变量
        let currentUser = null;
        let currentContact = null;
        let contacts = [];
        let messages = [];
        let token = null;
        let socket = null;
        let isTyping = false;
        let typingTimer = null;
        let friendRequests = [];
        let friendRequestsVisible = false;

        // API配置
        const API_BASE_URL = 'https://bicycle-active-hawaiian-officers.trycloudflare.com';

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            checkMobileView();
        });

        // 检查是否为移动端视图
        function checkMobileView() {
            const isMobile = window.innerWidth <= 768;
            const backButton = document.querySelector('.mobile-back-button');
            
            if (backButton) {
                if (isMobile) {
                    backButton.style.display = 'inline-block';
                } else {
                    backButton.style.display = 'none';
                }
            }
            
            // 监听窗口大小变化
            window.addEventListener('resize', function() {
                const isNowMobile = window.innerWidth <= 768;
                if (backButton) {
                    backButton.style.display = isNowMobile ? 'inline-block' : 'none';
                }
            });
        }

        // 检查认证状态
        function checkAuth() {
            token = localStorage.getItem('token');
            if (token) {
                validateToken();
            } else {
                showLoginPage();
            }
        }

        // 验证token
        async function validateToken() {
            try {
                const currentToken = localStorage.getItem('token');
                if (!currentToken) {
                    showLoginPage();
                    return;
                }
                
                const response = await fetch(`${API_BASE_URL}/api/users/me`, {
                    headers: {
                        'Authorization': `Bearer ${currentToken}`
                    }
                });
                
                if (response.ok) {
                    const userData = await response.json();
                    currentUser = userData.user || userData.data;
                    showChatPage();
                    initializeChat();
                } else {
                    localStorage.removeItem('token');
                    showLoginPage();
                }
            } catch (error) {
                console.error('Token验证失败:', error);
                localStorage.removeItem('token');
                showLoginPage();
            }
        }

        // 显示登录页面
        function showLoginPage() {
            document.getElementById('loginPage').classList.remove('hidden');
            document.getElementById('chatPage').classList.add('hidden');
        }

        // 显示聊天页面
        function showChatPage() {
            document.getElementById('loginPage').classList.add('hidden');
            document.getElementById('chatPage').classList.remove('hidden');
            document.getElementById('currentUserName').textContent = currentUser.username;
        }

        // 处理登录
        async function handleLogin(event) {
            event.preventDefault();
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const loginButton = event.target.querySelector('button[type="submit"]');
            const messageDiv = document.getElementById('loginMessage');

            loginButton.disabled = true;
            loginButton.textContent = '登录中...';

            try {
                const response = await fetch(`${API_BASE_URL}/api/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ username, password })
                });

                const data = await response.json();

                if (response.ok) {
                    const token = data.access_token;
                    localStorage.setItem('token', token);
                    messageDiv.innerHTML = '<div class="success-message">登录成功！</div>';
                    
                    // 获取当前用户信息
                    try {
                        const userResponse = await fetch(`${API_BASE_URL}/api/users/me`, {
                            headers: {
                                'Authorization': `Bearer ${token}`
                            }
                        });
                        
                        if (userResponse.ok) {
                            const userData = await userResponse.json();
                            currentUser = userData.user || userData.data;
                            setTimeout(() => {
                                showChatPage();
                                initializeChat();
                            }, 1000);
                        } else {
                            messageDiv.innerHTML = '<div class="error-message">获取用户信息失败</div>';
                        }
                    } catch (error) {
                        console.error('获取用户信息失败:', error);
                        messageDiv.innerHTML = '<div class="error-message">获取用户信息失败</div>';
                    }
                } else {
                    messageDiv.innerHTML = `<div class="error-message">${data.message || '登录失败'}</div>`;
                }
            } catch (error) {
                messageDiv.innerHTML = '<div class="error-message">网络错误，请检查服务器连接</div>';
            } finally {
                loginButton.disabled = false;
                loginButton.textContent = '登录';
            }
        }

        // 初始化聊天
        async function initializeChat() {
            await loadContacts();
            await loadFriendRequests();
            initializeWebSocket();
            setupWebSocketReconnection();
            startMessageSync(); // 启动智能消息同步
        }

        // 加载联系人
        async function loadContacts() {
            try {
                const currentToken = localStorage.getItem('token');
                if (!currentToken) {
                    showLoginPage();
                    return;
                }
                
                const response = await fetch(`${API_BASE_URL}/api/contacts`, {
                    headers: {
                        'Authorization': `Bearer ${currentToken}`
                    }
                });

                if (response.ok) {
                    contacts = await response.json();
                    renderContacts();
                } else if (response.status === 401) {
                    localStorage.removeItem('token');
                    showLoginPage();
                } else {
                    console.error('加载联系人失败');
                }
            } catch (error) {
                console.error('加载联系人错误:', error);
            }
        }

        // 渲染联系人列表
        function renderContacts(filteredContacts = contacts) {
            const contactsList = document.getElementById('contactsList');
            
            if (filteredContacts.length === 0) {
                contactsList.innerHTML = '<div class="empty-state">暂无联系人</div>';
                return;
            }

            contactsList.innerHTML = filteredContacts.map(contact => `
                <div class="contact-item ${currentContact && currentContact.id === contact.id ? 'active' : ''}" 
                     data-contact-id="${contact.id}"
                     onclick="selectContact(event, '${contact.id}', '${contact.username}')">
                    <div class="contact-avatar">
                        ${contact.username.charAt(0).toUpperCase()}
                    </div>
                    <div class="contact-info">
                        <div class="contact-name">${contact.username}</div>
                        <div class="contact-status ${contact.online ? 'online' : 'offline'}">
                            ${contact.online ? '● 在线' : '○ 离线'}
                        </div>
                    </div>
                </div>
            `).join('');
        }

        // 搜索联系人（好友）
        function searchContacts(query) {
            if (!contacts || contacts.length === 0) return;
            
            const filtered = contacts.filter(contact => 
                contact.username.toLowerCase().includes(query.toLowerCase())
            );
            renderContacts(filtered);
        }

        // 切换好友请求列表显示
        function toggleFriendRequests() {
            const requestsList = document.getElementById('friendRequestsList');
            friendRequestsVisible = !friendRequestsVisible;
            
            if (friendRequestsVisible) {
                requestsList.classList.add('show');
                loadFriendRequests(); // 每次显示时刷新列表
            } else {
                requestsList.classList.remove('show');
            }
        }

        // 加载好友请求列表
        async function loadFriendRequests() {
            try {
                const currentToken = localStorage.getItem('token');
                if (!currentToken) {
                    showLoginPage();
                    return;
                }
                
                const response = await fetch(`${API_BASE_URL}/api/friend-requests`, {
                    headers: {
                        'Authorization': `Bearer ${currentToken}`
                    }
                });

                if (response.ok) {
                    friendRequests = await response.json();
                    renderFriendRequests();
                    updateRequestsBadge();
                } else if (response.status === 401) {
                    localStorage.removeItem('token');
                    showLoginPage();
                } else {
                    console.error('加载好友请求失败');
                }
            } catch (error) {
                console.error('加载好友请求错误:', error);
            }
        }

        // 渲染好友请求列表
        function renderFriendRequests() {
            const requestsContent = document.getElementById('friendRequestsContent');
            
            if (friendRequests.length === 0) {
                requestsContent.innerHTML = '<div class="no-requests" style="padding: 30px; text-align: center; color: #999;">暂无好友请求</div>';
                return;
            }

            requestsContent.innerHTML = friendRequests.map(request => `
                <div class="friend-request-item" data-request-id="${request.id}">
                    <div class="friend-request-info">
                        <div class="friend-request-avatar">
                            ${request.username.charAt(0).toUpperCase()}
                        </div>
                        <div>
                            <div>${request.username}</div>
                            <div style="font-size: 12px; color: #999;">想添加你为好友</div>
                        </div>
                    </div>
                    <div class="friend-request-actions">
                        <button class="accept-button" onclick="acceptFriendRequest('${request.id}')">接受</button>
                        <button class="reject-button" onclick="rejectFriendRequest('${request.id}')">拒绝</button>
                    </div>
                </div>
            `).join('');
        }

        // 更新请求徽章
        function updateRequestsBadge() {
            const badge = document.getElementById('requestsBadge');
            if (friendRequests.length > 0) {
                badge.textContent = friendRequests.length;
                badge.style.display = 'block';
            } else {
                badge.style.display = 'none';
            }
        }

        // 接受好友请求
        async function acceptFriendRequest(requestId) {
            try {
                const currentToken = localStorage.getItem('token');
                if (!currentToken) {
                    showLoginPage();
                    return;
                }
                
                const response = await fetch(`${API_BASE_URL}/api/friend-requests/${requestId}/accept`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${currentToken}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    // 重新加载好友和请求列表
                    await loadContacts();
                    await loadFriendRequests();
                    alert('已成功添加好友！');
                } else {
                    const error = await response.json();
                    alert('接受好友请求失败: ' + (error.message || '未知错误'));
                }
            } catch (error) {
                console.error('接受好友请求错误:', error);
                alert('接受好友请求失败，请检查网络连接');
            }
        }

        // 拒绝好友请求
        async function rejectFriendRequest(requestId) {
            try {
                const currentToken = localStorage.getItem('token');
                if (!currentToken) {
                    showLoginPage();
                    return;
                }
                
                const response = await fetch(`${API_BASE_URL}/api/friend-requests/${requestId}/reject`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${currentToken}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    // 重新加载请求列表
                    await loadFriendRequests();
                } else {
                    const error = await response.json();
                    alert('拒绝好友请求失败: ' + (error.message || '未知错误'));
                }
            } catch (error) {
                console.error('拒绝好友请求错误:', error);
                alert('拒绝好友请求失败，请检查网络连接');
            }
        }

        // 显示添加好友模态框
        function showAddFriendModal() {
            const container = document.getElementById('userSearchContainer');
            container.style.display = 'flex';
            // 清空搜索结果
            document.getElementById('userSearchResults').innerHTML = '<div class="loading"><div class="spinner"></div>输入用户名进行搜索</div>';
        }

        // 隐藏添加好友模态框
        function hideAddFriendModal() {
            const container = document.getElementById('userSearchContainer');
            container.style.display = 'none';
        }

        // 搜索用户
        async function searchUsers(query) {
            if (!query.trim()) {
                document.getElementById('userSearchResults').innerHTML = '<div class="loading"><div class="spinner"></div>输入用户名进行搜索</div>';
                return;
            }

            try {
                const currentToken = localStorage.getItem('token');
                if (!currentToken) {
                    showLoginPage();
                    return;
                }
                
                const response = await fetch(`${API_BASE_URL}/api/search-users?q=${encodeURIComponent(query.trim())}`, {
                    headers: {
                        'Authorization': `Bearer ${currentToken}`
                    }
                });

                if (response.ok) {
                    const users = await response.json();
                    renderSearchResults(users);
                } else {
                    console.error('搜索用户失败');
                    document.getElementById('userSearchResults').innerHTML = '<div class="no-results">搜索失败，请重试</div>';
                }
            } catch (error) {
                console.error('搜索用户错误:', error);
                document.getElementById('userSearchResults').innerHTML = '<div class="no-results">搜索失败，请检查网络连接</div>';
            }
        }

        // 渲染搜索结果
        function renderSearchResults(users) {
            const resultsContainer = document.getElementById('userSearchResults');
            
            if (users.length === 0) {
                resultsContainer.innerHTML = '<div class="no-results">未找到匹配的用户</div>';
                return;
            }

            resultsContainer.innerHTML = users.map(user => `
                <div class="user-search-result-item" data-user-id="${user.id}">
                    <div class="user-search-info">
                        <div class="user-search-avatar">
                            ${user.username.charAt(0).toUpperCase()}
                        </div>
                        <div>
                            <div>${user.username}</div>
                            <div style="font-size: 12px; color: #999;">${user.online ? '在线' : '离线'}</div>
                        </div>
                    </div>
                    <button class="add-friend-button" onclick="sendFriendRequest('${user.id}', '${user.username}')">添加好友</button>
                </div>
            `).join('');
        }

        // 发送好友请求
        async function sendFriendRequest(userId, username) {
            try {
                const currentToken = localStorage.getItem('token');
                if (!currentToken) {
                    showLoginPage();
                    return;
                }
                
                const response = await fetch(`${API_BASE_URL}/api/friend-requests`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${currentToken}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username: username })
                });

                if (response.ok) {
                    alert(`已向 ${username} 发送好友请求！`);
                    hideAddFriendModal();
                } else {
                    const error = await response.json();
                    alert('发送好友请求失败: ' + (error.message || '未知错误'));
                }
            } catch (error) {
                console.error('发送好友请求错误:', error);
                alert('发送好友请求失败，请检查网络连接');
            }
        }

        // 点击页面其他区域关闭好友请求列表
        document.addEventListener('click', function(event) {
            const requestsButton = document.getElementById('friendRequestsButton');
            const requestsList = document.getElementById('friendRequestsList');
            
            if (friendRequestsVisible && !requestsButton.contains(event.target) && !requestsList.contains(event.target)) {
                toggleFriendRequests();
            }
        });

        // 选择联系人
        async function selectContact(event, contactId, contactName) {
            currentContact = { id: contactId, username: contactName };
            
            // 更新UI
            document.querySelectorAll('.contact-item').forEach(item => {
                item.classList.remove('active');
            });
            const contactElement = event.target.closest('.contact-item');
            contactElement.classList.add('active');
            
            // 清除未读标记
            const unreadBadge = contactElement.querySelector('.unread-badge');
            if (unreadBadge) {
                unreadBadge.remove();
            }
            
            document.getElementById('chatTitle').textContent = contactName;
            document.getElementById('chatStatus').textContent = '在线';
            
            await loadMessages();
            
            // 重置消息同步状态
            resetMessageSync();
            
            // 手机端选择联系人后自动隐藏联系人列表
            if (window.innerWidth <= 768) {
                hideContactsList();
            }
        }
        
        // 手机端显示联系人列表
        function showContactsList() {
            const sidebar = document.querySelector('.sidebar');
            sidebar.classList.add('active');
            // 即使在联系人列表视图，也要确保消息同步继续运行
            if (!socket || !socket.connected) {
                startMessageSync();
            }
        }
        
        // 手机端隐藏联系人列表
        function hideContactsList() {
            const sidebar = document.querySelector('.sidebar');
            sidebar.classList.remove('active');
            // 切换回聊天视图后，立即检查新消息
            checkNewMessages();
        }
        
        // 标记联系人为未读
        function markContactAsUnread(contactId) {
            const contactElement = document.querySelector(`[data-contact-id="${contactId}"]`);
            if (contactElement) {
                let unreadBadge = contactElement.querySelector('.unread-badge');
                if (!unreadBadge) {
                    // 创建未读消息徽章
                    unreadBadge = document.createElement('span');
                    unreadBadge.className = 'unread-badge';
                    unreadBadge.textContent = '1';
                    contactElement.appendChild(unreadBadge);
                } else {
                    // 增加未读计数
                    const currentCount = parseInt(unreadBadge.textContent) || 0;
                    unreadBadge.textContent = (currentCount + 1).toString();
                }
            }
        }

        // 加载消息
        async function loadMessages() {
            if (!currentContact) return;

            const messagesContainer = document.getElementById('messagesContainer');
            messagesContainer.innerHTML = '<div class="loading"><div class="spinner"></div>加载消息中...</div>';

            try {
                const currentToken = localStorage.getItem('token');
                if (!currentToken) {
                    showLoginPage();
                    return;
                }

                const response = await fetch(`${API_BASE_URL}/api/messages/${currentContact.id}`, {
                    headers: {
                        'Authorization': `Bearer ${currentToken}`
                    }
                });

                if (response.ok) {
                    messages = await response.json();
                    renderMessages();
                } else if (response.status === 401) {
                    localStorage.removeItem('token');
                    showLoginPage();
                } else {
                    messagesContainer.innerHTML = '<div class="empty-state">加载消息失败</div>';
                }
            } catch (error) {
                console.error('加载消息失败:', error);
                messagesContainer.innerHTML = '<div class="empty-state">加载消息失败，请重试</div>';
            }
        }

        // 渲染消息
        function renderMessages() {
            const messagesContainer = document.getElementById('messagesContainer');
            
            if (!messages || messages.length === 0) {
                messagesContainer.innerHTML = '<div class="empty-state"><i class="fas fa-comments" style="font-size: 48px; color: #ddd; margin-bottom: 10px;"></i><p>还没有消息，开始聊天吧！</p></div>';
                return;
            }

            messagesContainer.innerHTML = messages.map(msg => {
                const isSent = msg.sender_id === currentUser.id;
                const time = new Date(msg.timestamp).toLocaleTimeString('zh-CN', { 
                    hour: '2-digit', 
                    minute: '2-digit' 
                });
                
                let content = '';
                
                // 解析媒体消息内容
                if (msg.message_type === 'text') {
                    content = escapeHtml(msg.content || '');
                } else if (msg.message_type === 'image' || msg.message_type === 'file' || msg.message_type === 'audio') {
                    try {
                        console.log('媒体消息内容:', msg.content);
                        const mediaData = JSON.parse(msg.content || '{}');
                        const mediaId = mediaData.media_id || msg.content;
                        console.log('媒体ID:', mediaId, '消息类型:', msg.message_type);
                        
                        if (msg.message_type === 'image') {
                            content = `<img src="${API_BASE_URL}/api/messages/media/${mediaId}?token=${localStorage.getItem('token') || ''}" class="message-image" onclick="window.open(this.src)" onerror="this.onerror=null; this.style.display='none'; console.error('图片加载失败:', this.src); this.parentNode.innerHTML='<div class=\\'error-message\\'>图片加载失败</div>';">`;
                        } else if (msg.message_type === 'file') {
                            content = `
                                <div class="message-file" onclick="window.open('${API_BASE_URL}/api/messages/media/${mediaId}?token=${localStorage.getItem('token') || ''}')">
                                    <i class="fas fa-file"></i>
                                    <span>${mediaData.filename || '文件'}</span>
                                </div>
                            `;
                        } else if (msg.message_type === 'audio') {
                            content = `<audio controls class="message-audio" onerror="console.error('音频加载失败:', this.src)"><source src="${API_BASE_URL}/api/messages/media/${mediaId}?token=${localStorage.getItem('token') || ''}" type="${mediaData.content_type || 'audio/wav'}"></audio>`;
                        }
                    } catch (e) {
                        // 如果解析失败，显示原始内容
                        content = escapeHtml(msg.content || '');
                    }
                } else {
                    content = escapeHtml(msg.content || '');
                }
                
                return `
                    <div class="message ${isSent ? 'sent' : 'received'}">
                        ${!isSent ? `<div class="message-time">${time}</div>` : ''}
                        <div class="message-bubble">${content}</div>
                        ${isSent ? `<div class="message-time">${time}</div>` : ''}
                    </div>
                `;
            }).join('');
            
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        // 发送消息
        async function sendMessage() {
            if (!currentContact) return;

            const input = document.getElementById('messageInput');
            const content = input.value.trim();
            
            if (!content) return;

            const currentToken = localStorage.getItem('token');
            if (!currentToken) {
                showLoginPage();
                return;
            }

            // 立即清空输入框并添加临时消息
            input.value = '';
            const tempMessage = {
                id: 'temp_' + Date.now(),
                sender_id: localStorage.getItem('userId'),
                receiver_id: currentContact.id,
                content: content,
                message_type: 'text',
                timestamp: new Date().toISOString()
            };
            addMessageToChat(tempMessage);

            const messageData = {
                receiver_id: currentContact.id,
                message: {
                    type: 'text',
                    content: content
                }
            };

            try {
                const response = await fetch(`${API_BASE_URL}/api/messages/`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${currentToken}`
                    },
                    body: JSON.stringify(messageData)
                });

                if (response.ok) {
                    const result = await response.json();
                    
                    // 通过WebSocket发送消息（如果已连接）
                    if (socket && socket.connected) {
                        socket.emit('private_message', {
                            receiver_id: currentContact.id,
                            content: content
                        });
                    }
                    
                    // 移除临时消息（可选：等待服务器确认后更新ID）
                    const tempElement = document.querySelector(`[data-message-id="${tempMessage.id}"]`);
                    if (tempElement) {
                        tempElement.setAttribute('data-message-id', result.message_id);
                    }
                    
                } else if (response.status === 401) {
                    localStorage.removeItem('token');
                    showLoginPage();
                    
                    // 移除失败的临时消息
                    const tempElement = document.querySelector(`[data-message-id="${tempMessage.id}"]`);
                    if (tempElement) tempElement.remove();
                } else {
                    const error = await response.json();
                    alert('发送消息失败: ' + (error.message || '未知错误'));
                    
                    // 移除失败的临时消息
                    const tempElement = document.querySelector(`[data-message-id="${tempMessage.id}"]`);
                    if (tempElement) tempElement.remove();
                }
            } catch (error) {
                console.error('发送消息失败:', error);
                alert('发送消息失败，请检查网络连接');
                
                // 移除失败的临时消息
                const tempElement = document.querySelector(`[data-message-id="${tempMessage.id}"]`);
                if (tempElement) tempElement.remove();
            }
        }

        // 处理文件上传
        async function handleFileUpload(event) {
            const file = event.target.files[0];
            if (!file || !currentContact) return;

            const currentToken = localStorage.getItem('token');
            if (!currentToken) {
                showLoginPage();
                return;
            }

            const formData = new FormData();
            formData.append('file', file);

            try {
                const response = await fetch(`${API_BASE_URL}/api/messages/upload-media`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${currentToken}`
                    },
                    body: formData
                });

                if (response.ok) {
                    const mediaData = await response.json();
                    
                    // 创建媒体消息
                    const messageType = mediaData.content_type.startsWith('image/') ? 'image' : 
                                      mediaData.content_type.startsWith('audio/') ? 'audio' : 'file';
                    
                    const messageData = {
                        receiver_id: currentContact.id,
                        message: {
                            type: messageType,
                            content: JSON.stringify({
                                media_id: mediaData.media_id,
                                filename: mediaData.filename,
                                content_type: mediaData.content_type,
                                size: mediaData.size
                            })
                        }
                    };

                    // 立即添加临时媒体消息
                    const tempMediaMessage = {
                        id: 'temp_media_' + Date.now(),
                        sender_id: localStorage.getItem('userId'),
                        receiver_id: currentContact.id,
                        content: JSON.stringify({
                            media_id: mediaData.media_id,
                            filename: mediaData.filename,
                            content_type: mediaData.content_type,
                            size: mediaData.size
                        }),
                        message_type: messageType,
                        timestamp: new Date().toISOString()
                    };
                    addMessageToChat(tempMediaMessage);

                    // 发送媒体消息
                    const msgResponse = await fetch(`${API_BASE_URL}/api/messages/`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${currentToken}`
                        },
                        body: JSON.stringify(messageData)
                    });

                    if (msgResponse.ok) {
                        const result = await msgResponse.json();
                        
                        // 更新临时消息ID
                        const tempElement = document.querySelector(`[data-message-id="${tempMediaMessage.id}"]`);
                        if (tempElement) {
                            tempElement.setAttribute('data-message-id', result.message_id);
                        }
                        
                        // 通过WebSocket通知
                        if (socket && socket.connected) {
                            socket.emit('private_message', {
                                receiver_id: currentContact.id,
                                content: `[${messageType}] ${mediaData.filename}`
                            });
                        }
                    } else {
                        // 移除失败的临时消息
                        const tempElement = document.querySelector(`[data-message-id="${tempMediaMessage.id}"]`);
                        if (tempElement) tempElement.remove();
                    }
                    
                    event.target.value = '';
                    
                } else if (response.status === 401) {
                    localStorage.removeItem('token');
                    showLoginPage();
                } else {
                    alert('文件上传失败');
                }
            } catch (error) {
                console.error('文件上传错误:', error);
                alert('文件上传失败，请重试');
            }
        }

        // 处理键盘事件
        function handleKeyPress(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
        }

        // HTML转义函数
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // 无感添加单条消息到聊天界面
        function addMessageToChat(message) {
            const messagesContainer = document.getElementById('messagesContainer');
            if (!messagesContainer || !currentContact) return;

            const currentUserId = localStorage.getItem('userId');
            const isSent = message.sender_id === currentUserId;
            
            // 避免重复添加
            const existingMessage = document.querySelector(`[data-message-id="${message.id}"]`);
            if (existingMessage) return;

            // 创建新消息元素
            const messageElement = document.createElement('div');
            messageElement.className = `message ${isSent ? 'sent' : 'received'}`;
            messageElement.setAttribute('data-message-id', message.id);
            
            const time = new Date(message.timestamp).toLocaleTimeString('zh-CN', { 
                hour: '2-digit', 
                minute: '2-digit' 
            });
            
            let content = '';
            
            // 解析媒体消息内容
            if (message.message_type === 'text') {
                content = escapeHtml(message.content || '');
            } else if (message.message_type === 'image' || message.message_type === 'file' || message.message_type === 'audio') {
                try {
                    const mediaData = JSON.parse(message.content || '{}');
                    const mediaId = mediaData.media_id || message.content;
                    
                    if (message.message_type === 'image') {
                        content = `<img src="${API_BASE_URL}/api/messages/media/${mediaId}?token=${localStorage.getItem('token') || ''}" class="message-image" onclick="window.open(this.src)" onerror="this.onerror=null; this.style.display='none'; this.parentNode.innerHTML='<div class=\'error-message\'>图片加载失败</div>';">`;
                    } else if (message.message_type === 'file') {
                        content = `
                            <div class="message-file" onclick="window.open('${API_BASE_URL}/api/messages/media/${mediaId}?token=${localStorage.getItem('token') || ''}')">
                                <i class="fas fa-file"></i>
                                <span>${mediaData.filename || '文件'}</span>
                            </div>
                        `;
                    } else if (message.message_type === 'audio') {
                        content = `<audio controls class="message-audio" onerror="console.error('音频加载失败:', this.src)"><source src="${API_BASE_URL}/api/messages/media/${mediaId}?token=${localStorage.getItem('token') || ''}" type="${mediaData.content_type || 'audio/wav'}"></audio>`;
                    }
                } catch (e) {
                    content = escapeHtml(message.content || '');
                }
            } else {
                content = escapeHtml(message.content || '');
            }
            
            messageElement.innerHTML = `
                ${!isSent ? `<div class="message-time">${time}</div>` : ''}
                <div class="message-bubble">${content}</div>
                ${isSent ? `<div class="message-time">${time}</div>` : ''}
            `;
            
            // 添加到消息容器
            messagesContainer.appendChild(messageElement);
            
            // 滚动到底部
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        // 初始化WebSocket
        function initializeWebSocket() {
            const currentToken = localStorage.getItem('token');
            if (!currentToken) return;
            
            socket = io(API_BASE_URL, { 
                transports: ['websocket', 'polling'], // 允许回退到轮询
                auth: { 
                    token: currentToken 
                },
                timeout: 10000,
                reconnection: true,
                reconnectionAttempts: 10, // 增加重连尝试次数
                reconnectionDelay: 1000,
                reconnectionDelayMax: 8000, // 增加最大重连延迟
                autoConnect: true
            });

            socket.on('connect', () => {
                console.log('WebSocket连接成功');
                // 重连成功后停止轮询
                if (messageSyncInterval) {
                    clearInterval(messageSyncInterval);
                    messageSyncInterval = null;
                }
            });

            socket.on('new_message', (message) => {
                // 无论当前视图如何，都应该处理新消息
                if (currentContact && 
                    (message.sender_id === currentContact.id || message.receiver_id === currentContact.id)) {
                    // 无论是否在当前视图，都更新最后同步时间
                    lastSyncTime = message.timestamp;
                    
                    // 检查聊天区域是否可见（不是在联系人列表视图）
                    const sidebar = document.querySelector('.sidebar');
                    const isChatVisible = !sidebar.classList.contains('active') || window.innerWidth > 768;
                    
                    if (isChatVisible) {
                        addMessageToChat(message);
                    } else {
                        // 如果在联系人列表视图，标记有未读消息并更新UI
                        markContactAsUnread(message.sender_id);
                    }
                }
            });

            socket.on('user_status', (data) => {
                const contact = contacts.find(c => c.id === data.userId);
                if (contact) {
                    contact.online = data.online;
                    renderContacts();
                }
            });

            socket.on('disconnect', (reason) => {
                console.log('WebSocket断开连接:', reason);
                if (reason === 'io server disconnect') {
                    // 服务器主动断开，尝试重连
                    socket.connect();
                }
            });

            socket.on('connect_error', (error) => {
                console.error('WebSocket连接错误:', error);
                // 连接错误时启动轮询
                startMessageSync();
            });
            
            socket.on('reconnect_failed', () => {
                console.log('WebSocket重连失败，使用轮询模式');
                startMessageSync();
            });
        }

        // 登出
        function logout() {
            localStorage.removeItem('token');
            if (socket) {
                socket.disconnect();
            }
            token = null;
            currentUser = null;
            currentContact = null;
            contacts = [];
            messages = [];
            showLoginPage();
        }

        // 智能消息同步机制
        let messageSyncInterval = null;
        let lastSyncTime = null;
        
        // 启动消息同步
        function startMessageSync() {
            if (messageSyncInterval) {
                clearInterval(messageSyncInterval);
            }
            
            // 每3秒检查一次新消息（仅在WebSocket未连接时）
            messageSyncInterval = setInterval(() => {
                if (!socket || !socket.connected) {
                    checkNewMessages();
                }
            }, 3000);
        }
        
        // 检查新消息
        async function checkNewMessages() {
            if (!currentContact || !currentUser) return;
            
            try {
                const currentToken = localStorage.getItem('token');
                if (!currentToken) return;
                
                const url = lastSyncTime ? 
                    `${API_BASE_URL}/api/messages/${currentContact.id}?after=${lastSyncTime}` :
                    `${API_BASE_URL}/api/messages/${currentContact.id}`;
                
                const response = await fetch(url, {
                    headers: {
                        'Authorization': `Bearer ${currentToken}`
                    }
                });
                
                if (response.ok) {
                    const messages = await response.json();
                    if (messages && messages.length > 0) {
                        messages.forEach(message => {
                            // 避免重复添加
                            const existing = document.querySelector(`[data-message-id="${message.id}"]`);
                            if (!existing) {
                                addMessageToChat(message);
                            }
                        });
                        
                        // 更新最后同步时间
                        const latestMessage = messages[messages.length - 1];
                        lastSyncTime = latestMessage.timestamp;
                    }
                }
            } catch (error) {
                console.error('消息同步失败:', error);
            }
        }
        
        // 在切换联系人时重置同步状态
        function resetMessageSync() {
            lastSyncTime = null;
            if (currentContact) {
                checkNewMessages(); // 立即检查一次
            }
        }
        
        // 优化WebSocket重连机制
        function setupWebSocketReconnection() {
            let reconnectAttempts = 0;
            const maxReconnectAttempts = 5;
            
            function reconnect() {
                if (reconnectAttempts >= maxReconnectAttempts) {
                    console.log('WebSocket重连失败，使用轮询模式');
                    startMessageSync();
                    return;
                }
                
                reconnectAttempts++;
                console.log(`WebSocket重连尝试 ${reconnectAttempts}/${maxReconnectAttempts}`);
                
                setTimeout(() => {
                    initializeWebSocket();
                }, 2000 * reconnectAttempts); // 指数退避
            }
            
            // 监听WebSocket事件
            if (socket) {
                socket.on('disconnect', () => {
                    console.log('WebSocket断开，启动重连机制');
                    reconnect();
                });
                
                socket.on('connect', () => {
                    console.log('WebSocket重连成功');
                    reconnectAttempts = 0;
                    if (messageSyncInterval) {
                        clearInterval(messageSyncInterval);
                        messageSyncInterval = null;
                    }
                });
            }
        }
        

    </script>
</body>
</html>